package com.tangsm.spring.boot.api.controller;

import com.alibaba.fastjson2.JSON;
import com.tangsm.spring.boot.api.base.Result;
import com.tangsm.spring.boot.api.domain.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * API参数校验测试
 *
 * @author tangsm
 */
@Validated
@RestController
@RequestMapping("/valid")
public class ApiValidController {
    private static final Logger log = LoggerFactory.getLogger(ApiValidController.class);

    /**
     * 参数约束冲突校验
     * <p>参数约束冲突异常，方法所在的controller类上加入Validated注解</p>
     *
     * @return 响应信息
     */
    @GetMapping("/constraintViolationException")
    public Result<Map<String, Object>> constraintViolationException(
            @NotNull(message = "ID不能为空") Integer id,
            @NotBlank(message = "名称不能为空") String name,
            @Max(value = 200, message = "年龄不能超过200") Integer age) {
        log.info("参数约束冲突异常，请求参数，ID={}，name={}，age={}", id, name, age);
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", name);
        map.put("age", age);
        return Result.success(map);
    }

    /**
     * 表单提交参数校验
     *
     * @return 响应信息
     */
    @GetMapping("/bindException")
    public Result<UserInfo> bindException(@Valid UserInfo userInfo) {
        log.info("表单提交参数校验，请求参数：{}", JSON.toJSONString(userInfo));
        return Result.success(userInfo);
    }

    /**
     * Request Body请求参数校验
     *
     * @return 响应信息
     */
    @PostMapping("/methodArgumentNotValidException")
    public Result<UserInfo> methodArgumentNotValidException(@RequestBody @Validated UserInfo userInfo) {
        log.info("Request Body请求参数校验，请求参数：{}", JSON.toJSONString(userInfo));
        return Result.success(userInfo);
    }
}
